#include "LuaHandler.h"
#include <cocos2d.h>
#include "CCLuaEngine.h"
#include "tolua++.h"

#define COCOS2D_DEBUG 1

USING_NS_CC;

LuaHandler::LuaHandler()
	:_handler(0)
{
}

LuaHandler::LuaHandler(int handler)
	:_handler(handler)
{
}

LuaHandler::~LuaHandler()
{
	LuaEngine::getInstance()->removeScriptHandler(_handler);
}

bool LuaHandler::operator==(int handler)
{
	return _handler == handler;
}

LuaHandler& LuaHandler::operator=(int handler)
{
	_handler = handler;
	return *this;
}

void LuaHandler::pushInt(int value)
{
	lua_pushinteger(_state, value);
}

void LuaHandler::pushBool(bool value)
{
    lua_pushboolean(_state, value);
}

void LuaHandler::pushFloat(float value)
{
    lua_pushnumber(_state, value);
}

void LuaHandler::pushLongLong(long long a)
{
	lua_pushlstring(_state, (const char*)&a, sizeof(a));
}

void LuaHandler::pushString(const std::string& value)
{
	lua_pushstring(_state, value.c_str());
}

void LuaHandler::pushUserType(void* value, const char* name)
{
#ifdef COCOS2D_DEBUG
	luaL_getmetatable(_state, name); 
	if (lua_isnil(_state, -1)) {
		cocos2d::log("usertype\"%s\" not registed", name);
		lua_pop(_state, 1);
		lua_pushnil(_state);
		return;
	}
	lua_pop(_state, 1);
#endif
	tolua_pushusertype(_state, (void*)value, name);
}

/*
void LuaHandler::pushRTTI(void* value, const char* name)
{
	CCLOG("Cocos2dScriptProtocol::pushRTTI:%s !!!!!!!!!!unsafe!!!!!!!!!!", name);
	tolua_pushusertype(_state,(void*)value,name);
}
*/

void LuaHandler::prepare()
{
	_state = LuaEngine::getInstance()->getLuaStack()->getLuaState();
}

void LuaHandler::exec(int nArgs)
{
	LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(_handler, nArgs);
	_state = NULL;
}
